[ORG 0x7C00]
%include "oskernel/include/global.inc"

[SECTION .text]
[BITS 16]

global _start
_start:
    ; 清屏
    mov ax, 3
    int 0x10

    mov ax, 0
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov fs, ax
    mov gs, ax

    mov si, msg
    call print

    mov si, jmp_to_setup_msg
    call print

    ; 使用寄存器加载硬盘数据
    mov edi, SETUP_ADDR_BASE
    ; 从第一扇区开始读
    mov ecx, 1
    ; 读2个扇区
    mov bl, 2

    call read_hd

    jmp SETUP_ADDR_BASE

read_hd:
    mov dx, 0x1f2
    mov al, bl
    out dx, al

    mov dx, 0x1f3
    mov al, cl
    out dx, al

    mov dx, 0x1f4
    mov al, ch
    out dx, al

    shr ecx, 16
    mov dx, 0x1f5
    mov al, cl
    out dx, al

    mov dx, 0x1f6
    mov al, ch
    and al, 0b1111
    or al, 0b1110_0000
    out dx, al

    mov dx, 0x1f7
    mov al, 0x20
    out dx, al

    xor cx, cx
    mov cl, bl

.start_read:
    push cx

    call wait_hd_prepare
    call read_hd_data

    pop cx
    loop .start_read
.return:
    ret

wait_hd_prepare:
    mov dx, 0x1f7
.check:
    in al, dx
    and al, 0b1000_1000
    cmp al, 0b0000_1000
    jnz .check

    ret

read_hd_data:
    mov dx, 0x1f0
    mov cx, 256
.read_word:
    in ax, dx
    mov [edi], ax
    add edi, 2
    loop .read_word

    ret

print:
    mov ah, 0x0e
    mov bh, 0
    mov bl, 0x01
.loop:
    mov al, [si]
    cmp al, 0
    jz .done
    int 0x10

    inc si
    jmp .loop
.done:
    ret

msg: db "welcome to zhuguoyin's os", 10, 13, 0
jmp_to_setup_msg: db "jump to setup...", 10, 13, 0

times 510 - ($ - $$) db 0
dw 0xaa55